<template>
  <div>
    <span>全选:</span>
    <input type="checkbox" v-model="isAll" />
    <button @click="revFn">反选</button>
    <ul>
      <li v-for="(item, index) in arr" :key="index">
        <input type="checkbox" v-model="item.c" />
        <span>{{ item.name }}</span>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  methods: {
    revFn() {
      this.arr.forEach((item) => (item.c = !item.c));
    },
  },
  computed: {
    /*  //这样只能实现单选影响全选
    isAll() {
      //判断单选框是否每一个都被选中
      return this.arr.every((item) => item.c === true);
    }, */
    //完整写法
    isAll: {
      set(val) {
        //val是检测到全选框的状态 true/false
        console.log(val);
        //让单选框的状态和全选框的状态一样(将全选框的值给单选框)
        this.arr.forEach((ele) => {
          return (ele.c = val);
        });
      },
      get() {
        //计算所有的单选框是否都为true，选中全选框
        return this.arr.every((ele) => ele.c);
      },
    },
  },
  data() {
    return {
      arr: [
        {
          name: "猪八戒",
          c: false,
        },
        {
          name: "孙悟空",
          c: false,
        },
        {
          name: "唐僧",
          c: false,
        },
        {
          name: "白龙马",
          c: false,
        },
      ],
    };
  },
};
</script>